<?php

define('YOURLS_INFOS', true);

require_once("includes/load-yourls.php");
require_once("includes/userCake/config.php");
require_once("includes/functions-infos.php");

yourls_maybe_require_auth();

// Variables should be defined in yourls-loader.php, if not try GET request (old behavior of yourls-infos.php)
if( !isset( $keyword ) && isset( $_GET['id'] ) )
        $keyword = $_GET['id'];
if( !isset( $aggregate ) && isset( $_GET['all'] ) && $_GET['all'] == 1 && yourls_allow_duplicate_longurls() )
        $aggregate = true;

if ( !isset( $keyword ) ) {
        yourls_do_action( 'infos_no_keyword' );
        yourls_redirect( YOURLS_SITE, 302 );
}

// Get basic infos for this shortened URL
$keyword = yourls_sanitize_string( $keyword );
$longurl = yourls_get_keyword_longurl( $keyword );
$clicks = yourls_get_keyword_clicks( $keyword );
$timestamp = yourls_get_keyword_timestamp( $keyword );
$title = yourls_get_keyword_title( $keyword );

// Update title if it hasn't been stored yet
if( $title == '' ) {
        $title = yourls_get_remote_title( $longurl );
        yourls_edit_link_title( $keyword, $title );
}
$title=format_title($title, 32);
if ( $longurl === false ) {
        yourls_do_action( 'infos_keyword_not_found' );
        yourls_redirect( YOURLS_SITE, 302 );
}

if( yourls_do_log_redirect() ) {
        // Duplicate keywords, if applicable
        $keyword_list = yourls_get_duplicate_keywords( $longurl );

        // Fetch all information from the table log
        $table = YOURLS_DB_TABLE_LOG;

        if( $aggregate ) {
                $keywords = join( "', '", $keyword_list );
                // Fetch information for all keywords pointing to $longurl
                $hits = $ydb->get_results( "SELECT `shorturl`, min(click_time) click_time, `referrer`, `user_agent`, `country_code` FROM `$table` WHERE `shorturl` IN ( '$keywords' ) and user_agent not regexp 'bot|crawler|curl|spider' group by shorturl, ip_address;" );
        } else {
                // Fetch information for current keyword only
                $hits = $ydb->get_results( "SELECT min(click_time) click_time, `referrer`, `user_agent`, `country_code` FROM `$table` WHERE `shorturl` = '$keyword' and user_agent not regexp 'bot|crawler|curl|spider' group by shorturl, ip_address;" );
        }
        $referrers = array();
        $direct = $notdirect = 0;
        $countries = array();
        $dates = array();
        $list_of_days = array();
        $list_of_months = array();
        $list_of_years = array();
        $last_24h = array();

        // Loop through all results and build list of referrers, countries and hits per day
        $total_all = $total_ = 0;
        foreach( (array)$hits as $hit ) {
            $total_all++;
            extract( (array)$hit );

            if ( isset( $country_code ) && $country_code ) {
                if( !array_key_exists( $country_code, $countries ) )
                        $countries[$country_code] = 0;
                $countries[$country_code]++;
            }
            if( isset( $referrer ) ) {
                if ( $referrer == 'direct' ) {
                        $direct++;
                } else {
                        $notdirect++;
                        $host = yourls_get_domain( $referrer );
                        if( !array_key_exists( $host, $referrers ) )
                                $referrers[$host] = array( );
                        if( !array_key_exists( $referrer, $referrers[$host] ) )
                                $referrers[$host][$referrer] = 0;
                        $referrers[$host][$referrer]++;
                }
            }

            if( isset( $click_time ) ) {
                $now = intval( date('U') );

                preg_match('/(\d+)-(\d+)-(\d+)\s(\d+):(\d+):(\d+)/', $click_time, $matches);
                list( $temp, $year, $month, $day, $hour, $min, $sec ) = $matches;
                unset( $matches );

                // Build array of $dates[$year][$month][$day] = number of clicks
                if( !array_key_exists( $year, $dates ) )
                        $dates[$year] = array();
                if( !array_key_exists( $month, $dates[$year] ) )
                        $dates[$year][$month] = array();
                if( !array_key_exists( $day, $dates[$year][$month] ) )
                        $dates[$year][$month][$day] = 0;
                $dates[$year][$month][$day]++;

                // Build array of last 24 hours $last_24h[$hour] = number of click
                $then = strtotime( $click_time);
                if( ( $now >= $then ) && ( ( $now - $then ) < ( 24 * 60 * 60 ) ) ) {
                        $year = sprintf( "%02d", substr($year, -2) ); // 2009 -> 09
                        $diff = $now - strtotime( $click_time);
                        if( !array_key_exists( "$year-$month-$day-$hour", $last_24h ) )
                                $last_24h["$year-$month-$day-$hour"] = 0;
                        $last_24h["$year-$month-$day-$hour"]++;
                }
            }
        }


        // Sort dates, chronologically from [2007][12][24] to [2009][02][19]
        ksort( $dates );
        foreach( $dates as $year=>$months ) {
                ksort( $dates[$year] );
                foreach( $months as $month=>$day ) {
                        ksort( $dates[$year][$month] );
                }
        }

        // Get $list_of_days, $list_of_months, $list_of_years
        if( $dates ) {
                extract( yourls_build_list_of_days( $dates ) );

                // If the $last_24h doesn't have all the hours, insert missing hours with value 0
                for ($i = 23; $i >= 0; $i--) {
                        $h = date('y-m-d-H', $now - ($i * 60 * 60) );
                        if( !array_key_exists( $h, $last_24h ) ) {
                                $last_24h[$h] = 0;
                        }
                }
                ksort( $last_24h );
        }

        // Sort countries, most frequent first
        if ( $countries ) arsort( $countries );

        // Sort referrers. $referrer_sort is a array of most frequent domains
        arsort( $referrers );
        
        $keys = array_keys($referrers);
        $values = array_values($referrers);
        for ($i=count($referrers)-1;$i>0;$i--){
            $site = $keys[$i];
            $urls = $values[$i];
            $pos = 0;
            while(($pos = strpos($site, ".",$pos+1))!==FALSE) {
                $ssite = substr($site,$pos+1);
                if (isset($referrers[$ssite]))
                {
                    foreach ($urls as $url=>$count){
                        $referrers[$ssite][$url]=$count;
                    }
                    unset($referrers[$site]);
                    break;
                }
            }

        }
        $referrer_sort = array();
        $number_of_sites = count( array_keys( $referrers ) );
        foreach( $referrers as $site => $urls ) {
                if( count($urls) > 0 || $number_of_sites == 1 )
                        $referrer_sort[$site] = array_sum( $urls );
        }
        arsort($referrer_sort);
}      

$headtitle = "cos.as";
$onload="ih();";$alert="";

include_once 'includes/user.php';
include_once 'includes/header.php';
?>
<div id="all">
<div id="title"><a href="/">cos.as</a> sobre</div>
<div id="stats">
    <h2><?=$title?></h2>
    <div id="urls"><p class="inlineblock">URL corta: <img src="<?php echo YOURLS_SITE; ?>/favicon.ico"/>
<?php
    if( $aggregate ) {
        $i = 0;
        foreach( $keyword_list as $k ) {
            $i++;
            if ( $i == 1 ) {
                $link=yourls_link($k);
                yourls_html_link($link."+", $link);
            } else {
                yourls_html_link(yourls_link($k)."+", "/$k");
            }
            if ($i < count( $keyword_list ))
                echo ' + ';
        }
        $actions="";
        $init="<script>i2(false)</script>";
} else {
        $link=yourls_link($keyword);
        $init="<script>i2('$link')</script>";
        $ulink=urlencode($link);
        yourls_html_link($link);
        $unify="";
        if( count( $keyword_list ) > 1 )
            $unify = "<a class='un' href='$link+all' title='Ver estadísticas de todas las URLs cortas para esta página'><span class='icon'></span><u>unificar</u></a>";
        $actions = "<div class='act_actions'>$unify<a href='#' id='cp' class='cp'><span class='icon'></span><u>copiar</u></a><a class='tw' href='http://twitter.com/intent/tweet?text=$ulink'><span class='icon'></span><u>tuitear</u></a><a class='fb' href='http://www.facebook.com/share.php?u=$ulink'><span class='icon'></span><u>compartir</u></a></div>";
} ?></p><?=$actions?>
<p>URL larga: <img class="fix_images" src="<?php echo yourls_get_favicon_url( $longurl );?>" /> <?php yourls_html_link( $longurl, yourls_trim_long_string( $longurl ), 'longurl' ); ?></p>
</div>
<?php if( yourls_do_log_redirect() ) {

    $date = strftime("%e de %B de %Y a las %R", strtotime(yourls_get_keyword_timestamp($keyword)));
    $user = yourls_get_keyword_info($keyword, 'User_ID', "");
    if ($user!="") {
        $user = $ydb->get_var("SELECT Username FROM cosas_users where User_ID = $user");
        $user = "<br/>Usuario: $user";
    }
    echo "<p>Creación: $date$user</p><p>Visitas totales: $total_all</p>";
   echo "<div id='stats_left' class='inlineblock'>";

    echo "<div id='stats_hits'>";
    if ( $list_of_days ) {
        $graphs = array('24' => 'Ultimas 24 horas','7'  => 'Ultimos 7 días','30' => 'Ultimos 30 días','all'=> 'Todo el período');

        // Which graph to generate ?
        $do_all = $do_30 = $do_7 = $do_24 = false;
        $hits_all = array_sum( $list_of_days );
        $hits_30  = array_sum( array_slice( $list_of_days, -30 ) );
        $hits_7   = array_sum( array_slice( $list_of_days, -7 ) );
        $hits_24  = array_sum( $last_24h );
        if( $hits_all > 0 )
            $do_all = true; // graph for all days range
        if( $hits_30 > 0 && count( array_slice( $list_of_days, -30 ) ) == 30 )
            $do_30 = true; // graph for last 30 days
        if( $hits_7 > 0 && count( array_slice( $list_of_days, -7 ) ) == 7 )
            $do_7 = true; // graph for last 7 days
        if( $hits_24 > 0 )
            $do_24 = true; // graph for last 24 hours

        // Which graph to display ?
        $display_all = $display_30 = $display_7 = $display_24 = false;
        if( $do_24 ) {
            $display_24 = true;
            $selected_link = "24";
        } elseif ( $do_7 ) {
            $selected_link = "7";
            $display_7 = true;
        } elseif ( $do_30 ) {
            $selected_link = "30";
            $display_30 = true;
        } elseif ( $do_all ) {
            $selected_link = "all";
            $display_all = true;
        }

        echo "<ul id='lstat_lines' startopt='stat_line_$selected_link'>";
        if( $do_24 == true )
            echo "<li id='lstat_line_24' ".($display_24?"class='selected'":"")."><a onclick=\"chits('stat_line_24')\" href='#stat_line_24'>Ultimas 24 horas</a>";
        if( $do_7 == true )
            echo "<li id='lstat_line_7' ".($display_7?"class='selected'":"")."><a onclick=\"chits('stat_line_7')\" href='#stat_line_7'>Ultimos 7 días</a>";
        if( $do_30 == true )
            echo "<li id='lstat_line_30' ".($display_30?"class='selected'":"")."><a onclick=\"chits('stat_line_30')\" href='#stat_line_30'>Ultimos 30 días</a>";
        if( $do_all == true )
            echo "<li id='lstat_line_all' ".($display_all?"class='selected'":"")."><a onclick=\"chits('stat_line_all')\" href='#stat_line_all'>Todo el período</a>";
        echo "</ul>";

        // Generate, and display if applicable, each needed graph
        foreach( $graphs as $graph => $title ) {
            if( ${'do_'.$graph} == true ) {
                $selected = ( ${'display_'.$graph} === true ? 'selected' : '' );
                echo "<div id='dstat_line_$graph' class='toggle $selected'>";
                echo "<p>${'hits_'.$graph} visitas</p>";
                $labels_1 = $labels_2 = array();
                switch( $graph ) {
                    case '24':
                        // each key of $last_24h is of type "yy-mm-dd-hh"
                        $first_key = current( array_keys( $last_24h ) );
                        $last_key = end( array_keys( $last_24h ) );
                        // Get "dd/mm" of first and last key
                        $first_label = preg_replace( '/\d\d-(\d\d)-(\d\d)-\d\d/', '$2-$1', $first_key );
                        $last_label = preg_replace( '/\d\d-(\d\d)-(\d\d)-\d\d/', '$2-$1', $last_key );
                        $labels_2 = array( $first_label, $last_label);
                        // Get hh of each key
                        foreach( $last_24h as $k=>$v ) {
                                $labels_1[] = end( explode( '-', $k ) ); // 'hh'
                        }
                        yourls_stats_line( $last_24h, $labels_1, $labels_2 );
                        break;

                    case '7':
                    case '30':
                        // each key of $list_of_days is of type "yyyy-mm-dd"
                        $slice = array_slice( $list_of_days, intval( $graph ) * -1 );
                        foreach( $slice as $k=>$v ) {
                                // get "dd"
                                $labels_1[] = preg_replace( '/\d\d\d\d-\d\d-(\d\d)/', '$1', $k );
                        }
                        $first_key = current( array_keys( $slice ) );
                        $last_key = end( array_keys( $slice ) );
                        // Get "dd/mm" of first and last key
                        $first_label = preg_replace( '/(\d\d\d\d)-(\d\d)-\d\d/', '$2-$1', $first_key );
                        $last_label = preg_replace( '/(\d\d\d\d)-(\d\d)-\d\d/', '$2-$1', $last_key );
                        $labels_2 = array( $first_label, $last_label);

                        yourls_stats_line( $slice, $labels_1, $labels_2 );
                        unset( $slice );
                        break;

                    case 'all':
                        // get "yy-mm"
                        foreach( $list_of_days as $k=>$v ) {
                                $labels_1[] = preg_replace( '/(\d\d\d\d)-(\d\d)-\d\d/', '$2-$1', $k );
                        }
                        // take out duplicates
                        $labels_1 = array_unique( $labels_1 );
                        if (count($labels_1)<=2)
                        {
                            $labels_2 = $labels_1;
                            $labels_1 = array();
                            // get "yy-mm"
                            foreach( $list_of_days as $k=>$v ) {
                                    $labels_1[] = preg_replace( '/\d\d\d\d-\d\d-(\d\d)/', '$1', $k );
                            }
                            $labels_1 = array_unique( $labels_1 );

                        } else {
                            $labels_2 = yourls_array_granularity( $list_of_years, 30, false );
                        }

                        $labels_1 = yourls_array_granularity( $labels_1, 30, false );
                        yourls_stats_line( $list_of_days, $labels_1, $labels_2 );
                        break;
                }
                echo "</div>";
            }
        }
    } else {
        echo "<span>No se han producido visitas al enlace.</span>";
        
    }
    echo "</div>";

    echo "<div id='stats_refs'>";
    if ( $referrers ) {
        yourls_stats_pie( $referrer_sort, 4, '440x180' );
    } else {
        echo "<span>No se dispone información sobre los sitios<br/>web de procedencia de los visitantes.</span>";
    }
    echo "</div>";
    echo "</div>";

    echo "<div id='stats_maps' class='inlineblock'>";
    if ( $countries ) {
        echo "<span>Cargando mapa...</span>";
        yourls_stats_countries_map( $countries );
    } else {
        echo "<span>No se ha podido identificar la ubicación geográfica de los accesos a este enlace.</span>";
    }
    echo "</div>";
} // endif do log redirect ?>
<?=$init?>
</div>
<?include 'includes/footer.php';?>